package cn.xttc.edu.controller;


import cn.xttc.edu.entity.Admin;
import cn.xttc.edu.entity.ReturnMsg;
import cn.xttc.edu.service.AdminService;
import cn.xttc.edu.util.MyUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 杨磊
 * @since 2022-02-27
 */
@RestController
public class AdminController {
    private String filename = "";

    @Autowired
    private AdminService adminService;

    /**
     * 登录
     *
     * @param username 用户名
     * @param password 密码
     * @param session  session
     * @return 包装对象
     */
    @PostMapping("/login")
    public ReturnMsg login(String username, String password, String captcha, HttpSession session) {
        //辅助变量判断是否登陆成功
        boolean flag = false;
        //返回消息
        String msg = "";

        //校验验证码
        String sessionCaptcha = (String) session.getAttribute("captcha");
        if (!captcha.equalsIgnoreCase(sessionCaptcha)) {
            return ReturnMsg.fail("验证码错误，请重新输入");
        }

        //根据用户名查询管理员信息
        Admin admin = adminService.getOne(new QueryWrapper<Admin>().eq("name", username));
        if (admin != null) {
            String salt = admin.getSalt();
            String realPwd = MyUtil.getMD5(MyUtil.getMD5(password) + salt);
            if (!admin.getPassword().equals(realPwd)) {
                msg = "用户名或密码错误";
            } else {
                //判断是否被禁用
                if (admin.getStatus() != 1) {
                    return ReturnMsg.fail("该账户已被禁用");
                }

                //登录成功，获取当前小时
                int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);

                //欢迎词
                String welcomeMsg;

                if (hour < 9) {
                    welcomeMsg = "早上好";
                } else if (hour < 12) {
                    welcomeMsg = "上午好";
                } else if (hour < 14) {
                    welcomeMsg = "中午好";
                } else if (hour < 18) {
                    welcomeMsg = "下午好";
                } else {
                    welcomeMsg = "晚上好";
                }
                session.setAttribute("loginAdmin", admin);
                flag = true;
                msg = welcomeMsg + "，" + admin.getName();
            }
        } else {
            msg = "用户名或密码错误";
        }

        if (flag) {
            return ReturnMsg.success(msg);
        } else {
            return ReturnMsg.fail(msg);
        }
    }

    /**
     * 退出登录
     *
     * @param session session
     * @return 包装对象
     */
    @GetMapping("/logout")
    public ReturnMsg logout(HttpSession session) {
        session.removeAttribute("loginAdmin");
        return ReturnMsg.success("注销成功，即将返回登录页面");
    }

    /**
     * 查询管理员列表
     *
     * @param pn     页码
     * @param limit  每页显示条数
     * @param search 搜索
     * @param sort   排序列名
     * @param order  排序方式
     * @return json字符串
     */
    @GetMapping("/admins")
    public String getAdmins(
            @RequestParam("page") Integer pn,
            @RequestParam("limit") Integer limit,
            @RequestParam(value = "search", required = false, defaultValue = "") String search,
            @RequestParam("sort") String sort,
            @RequestParam("order") String order
    ) {
        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<Admin>().like("name", search);
        if ("asc".equalsIgnoreCase(order)) {
            adminQueryWrapper.orderByAsc(sort);
        } else if ("desc".equalsIgnoreCase(order)) {
            adminQueryWrapper.orderByDesc(sort);
        }
        Page<Admin> page = adminService.page(new Page<>(pn, limit), adminQueryWrapper);
        return MyUtil.formatReturnData(page);
    }

    /**
     * 根据姓名查询管理员
     *
     * @param name 姓名
     * @return 包装对象
     */
    @GetMapping("/admin")
    public ReturnMsg getAdminByName(@RequestParam("name") String name) {
        Admin admin = adminService.getOne(new QueryWrapper<Admin>().eq("name", name));
        if (admin != null) {
            return ReturnMsg.fail("该用户名已被占用");
        } else {
            return ReturnMsg.success("");
        }
    }

    /**
     * 添加管理员
     *
     * @param admin 管理员
     * @return 包装对象
     */
    @PostMapping("/admin")
    public ReturnMsg addAdmin(Admin admin) {
        //生成6位随机盐值数，加密密码，设置默认头像和状态
        String salt = String.format("%06d", new Random().nextInt(999999));
        admin
                .setPassword(MyUtil.getMD5(MyUtil.getMD5(admin.getPassword()) + salt))
                .setPic("default.webp")
                .setStatus(1);
        try {
            adminService.save(admin);
            return ReturnMsg.success("添加成功");
        } catch (Exception e) {
            return ReturnMsg.fail("添加失败");
        }
    }

    /**
     * 回显头像
     *
     * @param pic     图片
     * @param request request
     * @return json字符串
     */
    @PostMapping("/admin/pic")
    public Object handlePic(MultipartFile pic, HttpServletRequest request) {
        //生成要保存的文件名
        filename = MyUtil.getUUIDFileName() + MyUtil.getFileType(Objects.requireNonNull(pic.getOriginalFilename()));
        //得到项目中图片存储的路径
        String path = "D:\\workplace\\Java_workplace\\JiAnTransport\\src\\main\\webapp\\static\\admin_pic";
        String serverPath = request.getServletContext().getRealPath("/static/admin_pic");

        //转存
        try {
            FileUtils.copyInputStreamToFile(pic.getInputStream(), new File(path + File.separator + filename));
            FileUtils.copyInputStreamToFile(pic.getInputStream(), new File(serverPath + File.separator + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //返回客户端JSON对象,封装图片的路径,为了在页面实现立即回显
        JSONObject object = new JSONObject();
        object.put("imgurl", filename);
        return object.toString();
    }

    /**
     * 修改密码
     *
     * @param oldPwd  旧密码
     * @param newPwd  新密码
     * @param session session
     * @return 包装对象
     */
    @PutMapping("/editPwd")
    public ReturnMsg editPwd(
            @RequestParam("oldPwd") String oldPwd,
            @RequestParam("newPwd") String newPwd,
            HttpSession session
    ) {
        Admin loginAdmin = (Admin) session.getAttribute("loginAdmin");
        String password = loginAdmin.getPassword();
        String salt = loginAdmin.getSalt();
        if (!Objects.equals(MyUtil.getMD5(MyUtil.getMD5(oldPwd) + salt), password)) {
            return ReturnMsg.fail("原密码输入错误");
        } else {
            try {
                adminService.updateById(loginAdmin.setPassword(MyUtil.getMD5(newPwd)));
                session.removeAttribute("loginAdmin");
                return ReturnMsg.success("密码修改成功，请重新登录");
            } catch (Exception e) {
                return ReturnMsg.fail("密码修改失败");
            }
        }
    }

    /**
     * 修改头像
     *
     * @param session session
     * @return 包装对象
     */
    @PutMapping("/editPic")
    public ReturnMsg editPic(HttpSession session) {
        Admin loginAdmin = (Admin) session.getAttribute("loginAdmin");
        try {
            adminService.updateById(loginAdmin.setPic(filename));
            return ReturnMsg.success("头像修改成功");
        } catch (Exception e) {
            return ReturnMsg.fail("头像修改失败");
        }
    }

    /**
     * 修改管理员状态
     */
    @PutMapping("/admin/{id}")
    public ReturnMsg editAdmin(Admin admin) {
        try {
            adminService.updateById(admin);
            return ReturnMsg.success("修改成功");
        } catch (Exception e) {
            return ReturnMsg.fail("更新失败");
        }
    }

    /**
     * 批量修改管理员状态
     *
     * @param list 要修改的象集合
     * @return 包装对象
     */
    @PutMapping("/admin")
    public ReturnMsg editBatchCarStatus(@RequestBody List<Admin> list) {
        try {
            adminService.updateBatchById(list);
            return ReturnMsg.success("修改成功");
        } catch (Exception e) {
            return ReturnMsg.fail("修改失败");
        }
    }

    /**
     * 单个删除和批量删除
     *
     * @param ids id字符串
     * @return 封装对象
     */
    @DeleteMapping("/admin/{ids}")
    public ReturnMsg deleteCars(@PathVariable("ids") String ids) {
        if (ids.contains("-")) {
            //批量删除
            List<Integer> delIds = new ArrayList<>();
            String[] strIds = ids.split("-");
            //组装id的集合
            for (String string : strIds) {
                delIds.add(Integer.parseInt(string));
            }
            try {
                adminService.removeBatchByIds(delIds);
            } catch (Exception e) {
                return ReturnMsg.fail("删除失败");
            }
        } else {
            //单个删除
            Integer id = Integer.parseInt(ids);
            try {
                adminService.removeById(id);
            } catch (Exception e) {
                return ReturnMsg.fail("删除失败");
            }
        }
        return ReturnMsg.success("删除成功");
    }
}

